﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VFTray
{
	public partial class DlgSaveAsRecipe : Form
	{
		public DlgSaveAsRecipe()
		{
			InitializeComponent();
			Load += (s, e) =>
			  {
				  textBoxCurrent.Text = GlobalParams.CD.RecipeName;
			  };
		}

		public string RecipeName => textBoxNewRecipe.Text;
		public static void CopyFolder(string sourceFolder, string destFolder)
		{
			if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder);

			string[] files = Directory.GetFiles(sourceFolder);
			foreach (string file in files)
			{
				string name = Path.GetFileName(file);
				string dest = Path.Combine(destFolder, name);
				File.Copy(file, dest, true);
			}

			string[] folders = Directory.GetDirectories(sourceFolder);
			foreach (string folder in folders)
			{
				string name = Path.GetFileName(folder);
				string dest = Path.Combine(destFolder, name);
				CopyFolder(folder, dest);
			}
		}

		private void buttonCancel_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;
			Close();
		}

		private void buttonOK_Click(object sender, EventArgs e)
		{
			if(textBoxNewRecipe.Text.Length==0)
			{
				MessageBox.Show(this, "指定新配方名", "警告");
				textBoxNewRecipe.Focus();
				return;
			}

			string nr_name = textBoxNewRecipe.Text;
			string nr_dir = Path.Combine(GlobalParams.CD.RecipeBootPath, nr_name);
			if (Directory.Exists(nr_dir))
			{
				MessageBox.Show(this, "配方已经存在" + Environment.NewLine + nr_name, "警告");
				textBoxNewRecipe.Focus();
				textBoxNewRecipe.SelectAll();
				return;
			}

			string old_dir = Path.Combine(GlobalParams.CD.RecipeBootPath, GlobalParams.CD.RecipeName);
			CopyFolder(old_dir, nr_dir);
			try
			{
				string f_xml = Path.Combine(nr_dir, GlobalParams.CD.RecipeName + ".xml");
				string new_xml = Path.Combine(nr_dir, nr_name + ".xml");

				File.Move(f_xml, new_xml);
				f_xml += ".bak";
				new_xml += ".bak";
				File.Move(f_xml, new_xml);
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, "" + Environment.NewLine + ex.Message, "ERROR");
			}

			DialogResult = DialogResult.OK;
			Close();
		}
	}
}
